#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int fd;
	struct sockaddr_in addr;
	struct timeval timeo = {3, 0};

	fd = socket(AF_INET, SOCK_STREAM, 0);
	
	if(argc == 4)
	{
		socklen_t len = sizeof(timeo);
		timeo.tv_sec = atoi(argv[3]);
		setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);
	}

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(argv[1]);
	addr.sin_port = htons(atoi(argv[2]));

#define select_timeout
	 
#ifdef select_timeout
	fd_set wset;
	int ret = 0;
	int error = 0;
	int flag = 0;
	socklen_t lenth = 0;
	flag = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, flag | O_NONBLOCK);


	if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) 
	{
		FD_ZERO(&wset);
		FD_SET(fd, &wset);

		ret=select(fd+1,NULL,&wset,NULL,&timeo);
		if(ret <= 0)
		{
			printf("connect error\n");		
			return -1;
		}
		getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &lenth);
		printf("connected  error=%d %d\n", error, ret);
		return 0;
	}

#else
	time_t t = time(NULL);
	if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
		if (errno == EINPROGRESS) {
			fprintf(stderr, "timeout = %ld\n", time(NULL) - t);
			return -1;
		}
		perror("connect ");
		fprintf(stderr, "connect time=%ld\n",time(NULL) - t);
		return 0;
	}
	printf("connected\n");
#endif

	return 0;
}
